'use strict';

const Service = require('egg').Service;

class RecommendationService extends Service {

  // 获取实时天气信息
  async getWeatherInfo(city = '北京') {
    try {
      // 和风天气API配置
      const weatherToken = this.config.weather?.token || 'K6WKR2F6KX'; // JWT身份认证令牌
      const apiHost = this.config.weather?.apiHost || 'devapi.qweather.com'; // API Host地址
console.log('apiHost',apiHost)
      // 如果没有配置真实的token和host，返回模拟数据
      if (weatherToken === 'devapitoken' || apiHost === 'devapi.qweather.com') {
        console.log('使用模拟天气数据，请配置真实的weatherToken和apiHost');
        return this.getMockWeatherData(city);
      }

      // 先获取城市ID
      const locationUrl = `https://${apiHost}/v7/city/lookup?location=${encodeURIComponent(city)}&key=${weatherToken}`;
      const locationResponse = await this.ctx.curl(locationUrl, {
        method: 'GET',
        headers: {
          'Accept-Encoding': 'gzip'
        },
        dataType: 'json',
        timeout: 5000,
        gzip: true
      });

      if (locationResponse.status !== 200 || !locationResponse.data.location?.[0]) {
        console.log('获取城市信息失败，使用模拟数据');
        return this.getMockWeatherData(city);
      }

      const locationId = locationResponse.data.location[0].id;

      // 获取实时天气
      const weatherUrl = `https://${apiHost}/v7/weather/now?location=${locationId}&key=${weatherToken}`;
      const weatherResponse = await this.ctx.curl(weatherUrl, {
        method: 'GET',
        headers: {
          'Accept-Encoding': 'gzip'
        },
        dataType: 'json',
        timeout: 5000,
        gzip: true
      });

      if (weatherResponse.status !== 200 || !weatherResponse.data.now) {
        console.log('获取天气信息失败，使用模拟数据');
        return this.getMockWeatherData(city);
      }

      const weather = weatherResponse.data.now;

      return {
        temperature: parseInt(weather.temp),
        condition: weather.text,
        humidity: parseInt(weather.humidity),
        windSpeed: weather.windSpeed,
        icon: weather.icon,
        feelsLike: parseInt(weather.feelsLike),
        city: city,
        updateTime: weather.obsTime
      };
    } catch (error) {
      console.error('获取天气信息失败:', error);
      return this.getMockWeatherData(city);
    }
  }

  // 获取模拟天气数据
  getMockWeatherData(city) {
    const mockData = {
      北京: { temp: 15, condition: '晴', humidity: 45 },
      上海: { temp: 18, condition: '多云', humidity: 60 },
      广州: { temp: 25, condition: '晴', humidity: 70 },
      深圳: { temp: 26, condition: '晴', humidity: 65 }
    };

    const data = mockData[city] || mockData['北京'];

    return {
      temperature: data.temp,
      condition: data.condition,
      humidity: data.humidity,
      windSpeed: '3',
      icon: '100',
      feelsLike: data.temp + 2,
      city: city,
      updateTime: new Date().toISOString(),
      isMock: true
    };
  }

  // 基于天气的搭配推荐
  async getWeatherBasedRecommendations(userId, weatherInfo) {
    const { weather, temperature, location } = weatherInfo;
    console.log(`🌤️ 开始天气推荐: ${temperature}°C ${weather}`);

    // 获取用户所有衣服
    const { Op } = this.app.Sequelize;
    const allClothing = await this.ctx.model.Clothing.findAll({
      where: {
        user_id: userId,
        status: 'available'
      },
      include: [{
        model: this.ctx.model.Category,
        as: 'category'
      }]
    });

    console.log(`👕 用户衣柜中有${allClothing.length}件衣服`);

    if (allClothing.length === 0) {
      return {
        recommendations: [],
        analysis: '您的衣柜还没有衣服呢！请先添加一些衣服。',
        context: weatherInfo
      };
    }

    // 智能天气搭配生成
    const recommendations = this.generateWeatherSmartOutfits(allClothing, weatherInfo);

    // 保存推荐记录
    const recommendation = await this.ctx.model.Recommendation.create({
      user_id: userId,
      type: 'weather',
      title: `${temperature}°C ${weather} 天气推荐`,
      description: `根据当前天气条件为您推荐的搭配`,
      clothing_ids: JSON.stringify(recommendations.map(r => r.clothingIds)),
      context: JSON.stringify(weatherInfo),
      confidence_score: 0.8,
      expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000)
    });

    return {
      id: recommendation.id,
      type: 'weather',
      title: recommendation.title,
      description: recommendation.description,
      recommendations,
      context: weatherInfo
    };
  }

  // 基于场合的搭配推荐
  async getOccasionBasedRecommendations(userId, occasionInfo) {
    const { occasion, style } = occasionInfo;
    console.log(`👔 开始场合推荐: ${occasion} - ${style || '无特定风格'}`);

    // 获取用户所有衣服
    const allClothing = await this.ctx.model.Clothing.findAll({
      where: {
        user_id: userId,
        status: 'available'
      },
      include: [{
        model: this.ctx.model.Category,
        as: 'category'
      }]
    });

    console.log(`👕 用户衣柜中有${allClothing.length}件衣服`);

    if (allClothing.length === 0) {
      return {
        recommendations: [],
        analysis: '您的衣柜还没有衣服呢！请先添加一些衣服。',
        context: occasionInfo
      };
    }

    // 智能场合搭配生成
    const recommendations = this.generateOccasionSmartOutfits(allClothing, occasionInfo);

    // 保存推荐记录
    const recommendation = await this.ctx.model.Recommendation.create({
      user_id: userId,
      type: 'occasion',
      title: `${this.getOccasionDisplayName(occasion)} 场合推荐`,
      description: `为${this.getOccasionDisplayName(occasion)}场合精心挑选的搭配`,
      clothing_ids: JSON.stringify(recommendations.map(r => r.clothingIds)),
      context: JSON.stringify(occasionInfo),
      confidence_score: 0.75
    });

    return {
      id: recommendation.id,
      type: 'occasion',
      title: recommendation.title,
      description: recommendation.description,
      recommendations,
      context: occasionInfo
    };
  }

  // 基于颜色搭配的推荐
  async getColorBasedRecommendations(userId, colorInfo) {
    const { baseColor, colorScheme = 'complementary' } = colorInfo;
    console.log(`🎨 开始颜色搭配推荐: ${baseColor} - ${colorScheme}`);

    // 获取用户所有衣服
    const allClothing = await this.ctx.model.Clothing.findAll({
      where: {
        user_id: userId,
        status: 'available'
      },
      include: [{
        model: this.ctx.model.Category,
        as: 'category'
      }]
    });

    console.log(`👕 用户衣柜中有${allClothing.length}件衣服`);

    if (allClothing.length === 0) {
      return {
        recommendations: [],
        analysis: '您的衣柜还没有衣服呢！请先添加一些衣服。',
        context: colorInfo
      };
    }

    // 智能颜色搭配生成
    const recommendations = this.generateColorSmartOutfits(allClothing, colorInfo);

    // 保存推荐记录
    const recommendation = await this.ctx.model.Recommendation.create({
      user_id: userId,
      type: 'color',
      title: `${baseColor} ${this.getColorSchemeDisplayName(colorScheme)}`,
      description: `基于${baseColor}的${this.getColorSchemeDisplayName(colorScheme)}方案`,
      clothing_ids: JSON.stringify(recommendations.map(r => r.clothingIds)),
      context: JSON.stringify(colorInfo),
      confidence_score: 0.7
    });

    return {
      id: recommendation.id,
      type: 'color',
      title: recommendation.title,
      description: recommendation.description,
      recommendations,
      context: colorInfo
    };
  }

  // 基于个人偏好的推荐
  async getPersonalBasedRecommendations(userId) {
    // 获取用户偏好
    const preferences = await this.ctx.model.UserPreference.findAll({
      where: { user_id: userId }
    });

    // 获取用户的穿搭历史
    const wearHistory = await this.ctx.model.WearRecord.findAll({
      where: { user_id: userId },
      include: [{
        model: this.ctx.model.Outfit,
        as: 'outfit',
        include: [{
          model: this.ctx.model.Clothing,
          as: 'clothes'
        }]
      }],
      order: [['created_at', 'DESC']],
      limit: 50
    });

    // 分析用户偏好
    const analysis = this.analyzeUserPreferences(preferences, wearHistory);

    // 基于分析结果生成推荐
    const clothing = await this.ctx.model.Clothing.findAll({
      where: {
        user_id: userId,
        status: 'available'
      }
    });

    const recommendations = this.generatePersonalizedRecommendations(clothing, analysis);

    return {
      type: 'personal',
      title: '个人偏好推荐',
      description: '基于您的穿搭习惯和偏好的个性化推荐',
      recommendations,
      analysis
    };
  }

  // 生成搭配组合
  generateOutfitCombinations(clothing, options = {}) {
    const { maxCombinations = 5 } = options;
    const combinations = [];

    console.log(`开始生成搭配组合，衣服数量：${clothing.length}`);

    if (clothing.length === 0) {
      console.log('没有衣服数据，返回空推荐');
      return [];
    }

    // 按分类分组
    const clothingByCategory = {};
    clothing.forEach(item => {
      const categoryName = item.category?.name || 'other';
      if (!clothingByCategory[categoryName]) {
        clothingByCategory[categoryName] = [];
      }
      clothingByCategory[categoryName].push(item);
    });

    console.log('衣服分类统计:', Object.keys(clothingByCategory).map(key => `${key}: ${clothingByCategory[key].length}`));

    // 获取各类衣服 - 更灵活的分类匹配
    const tops = this.getClothesByType(clothingByCategory, ['上装', '上衣', 'tops', 'shirt', 'blouse', 't-shirt']);
    const bottoms = this.getClothesByType(clothingByCategory, ['下装', '裤子', '裙子', 'bottoms', 'pants', 'skirt', 'jeans']);
    const outerwear = this.getClothesByType(clothingByCategory, ['外套', 'outerwear', 'jacket', 'coat']);
    const shoes = this.getClothesByType(clothingByCategory, ['鞋子', '鞋', 'shoes', 'sneakers', 'boots']);
    const accessories = this.getClothesByType(clothingByCategory, ['配饰', '包', '帽子', 'accessories', 'bag', 'hat', 'jewelry']);

    // 如果没有上装和下装，尝试使用所有衣服
    if (tops.length === 0 && bottoms.length === 0) {
      console.log('没有找到上装和下装，使用所有衣服生成单品推荐');
      for (let i = 0; i < Math.min(maxCombinations, clothing.length); i++) {
        const item = clothing[i];
        combinations.push({
          clothingIds: [item.id],
          items: [item],
          score: 0.6,
          tags: ['单品推荐'],
          reason: '基础单品推荐'
        });
      }
      return combinations;
    }

    console.log(`找到衣服分类: 上装${tops.length}件, 下装${bottoms.length}件, 外套${outerwear.length}件, 鞋子${shoes.length}件, 配饰${accessories.length}件`);

    // 生成搭配组合 - 改进的算法
    const strategies = [
      { name: '基础搭配', includeOuterwear: false, includeAccessories: 0.3 },
      { name: '完整搭配', includeOuterwear: true, includeAccessories: 0.7 },
      { name: '简约搭配', includeOuterwear: false, includeAccessories: 0.1 },
      { name: '层次搭配', includeOuterwear: true, includeAccessories: 0.9 }
    ];

    for (let strategyIndex = 0; strategyIndex < strategies.length && combinations.length < maxCombinations; strategyIndex++) {
      const strategy = strategies[strategyIndex];

      // 为每种策略生成搭配
      const maxTopsForStrategy = Math.min(2, tops.length);
      const maxBottomsForStrategy = Math.min(2, bottoms.length);

      for (let i = 0; i < maxTopsForStrategy && combinations.length < maxCombinations; i++) {
        for (let j = 0; j < maxBottomsForStrategy && combinations.length < maxCombinations; j++) {
          const currentItems = [];
          const currentIds = [];

          // 添加上装
          if (tops[i]) {
            currentItems.push(tops[i]);
            currentIds.push(tops[i].id);
          }

          // 添加下装
          if (bottoms[j]) {
            currentItems.push(bottoms[j]);
            currentIds.push(bottoms[j].id);
          }

          // 根据策略添加外套
          if (strategy.includeOuterwear && outerwear.length > 0) {
            const outerIndex = strategyIndex % outerwear.length;
            currentItems.push(outerwear[outerIndex]);
            currentIds.push(outerwear[outerIndex].id);
          }

          // 添加鞋子（如果有）
          if (shoes.length > 0) {
            const shoeIndex = (i + j) % shoes.length;
            currentItems.push(shoes[shoeIndex]);
            currentIds.push(shoes[shoeIndex].id);
          }

          // 根据策略添加配饰
          if (accessories.length > 0 && Math.random() < strategy.includeAccessories) {
            const accessoryIndex = (i + j + strategyIndex) % accessories.length;
            currentItems.push(accessories[accessoryIndex]);
            currentIds.push(accessories[accessoryIndex].id);
          }

          if (currentItems.length >= 2) { // 至少要有2件衣服才算搭配
            const combination = {
              clothingIds: currentIds,
              items: currentItems,
              score: this.calculateCombinationScore(currentItems),
              tags: this.getCombinationTags(currentItems),
              reason: `${strategy.name} - ${this.generateCombinationReason(currentItems)}`
            };

            combinations.push(combination);
          }
        }
      }
    }

    console.log(`生成了${combinations.length}个搭配组合，每个搭配平均包含${combinations.length > 0 ? (combinations.reduce((sum, c) => sum + c.items.length, 0) / combinations.length).toFixed(1) : 0}件衣服`);

    // 去重并排序
    const uniqueCombinations = this.removeDuplicateCombinations(combinations);
    return uniqueCombinations.sort((a, b) => b.score - a.score).slice(0, maxCombinations);
  }

  // 生成搭配理由
  generateCombinationReason(items) {
    const reasons = [];

    if (items.length >= 2) {
      reasons.push('经典搭配');
    }

    const colors = items.map(item => item.color).filter(Boolean);
    if (colors.length > 1) {
      reasons.push('颜色协调');
    }

    const categories = items.map(item => item.category?.name).filter(Boolean);
    if (categories.includes('上装') && categories.includes('下装')) {
      reasons.push('上下搭配');
    }

    return reasons.length > 0 ? reasons.join('，') : '为您推荐';
  }

  // 计算搭配组合评分
  calculateCombinationScore(items) {
    let score = 0.5; // 基础分

    // 颜色搭配评分
    const colors = items.map(item => item.color).filter(Boolean);
    if (this.isColorHarmony(colors)) {
      score += 0.2;
    }

    // 风格一致性评分
    const styles = items.map(item => item.style).filter(Boolean);
    if (this.isStyleConsistent(styles)) {
      score += 0.2;
    }

    // 季节适配评分
    const seasons = items.map(item => item.season).filter(Boolean);
    if (this.isSeasonConsistent(seasons)) {
      score += 0.1;
    }

    return Math.min(1.0, score);
  }

  // 颜色搭配辅助方法
  getComplementaryColors(baseColor) {
    const colorMap = {
      red: ['green', 'white', 'black'],
      blue: ['orange', 'white', 'navy'],
      yellow: ['purple', 'blue', 'white'],
      green: ['red', 'beige', 'brown'],
      purple: ['yellow', 'white', 'gray'],
      orange: ['blue', 'white', 'brown']
    };
    return colorMap[baseColor.toLowerCase()] || ['white', 'black', 'gray'];
  }

  getAnalogousColors(baseColor) {
    // 实现类似色搭配逻辑
    return [baseColor, 'white', 'gray'];
  }

  getTriadicColors(baseColor) {
    // 实现三角色搭配逻辑
    return [baseColor, 'white', 'black'];
  }

  getMonochromaticColors(baseColor) {
    // 实现单色搭配逻辑
    return [baseColor, 'white', 'black'];
  }

  // 其他辅助方法
  isColorHarmony(colors) {
    // 简单的颜色和谐判断
    return colors.length <= 3;
  }

  isStyleConsistent(styles) {
    // 风格一致性判断
    if (styles.length <= 1) return true;
    return styles.every(style => style === styles[0]);
  }

  isSeasonConsistent(seasons) {
    // 季节一致性判断
    if (seasons.length <= 1) return true;
    return seasons.every(season => season === seasons[0] || season === 'all');
  }

  getCombinationTags(items) {
    const allTags = items.flatMap(item => item.tags || []);
    return [...new Set(allTags.map(tag => tag.name))];
  }

  // 分析用户偏好（智能学习）
  analyzeUserPreferences(preferences, wearHistory) {
    console.log('🧠 开始分析用户偏好...');

    const analysis = {
      preferredColors: [],
      preferredStyles: [],
      preferredBrands: [],
      preferredCategories: [],
      colorFrequency: {},
      styleFrequency: {},
      brandFrequency: {},
      categoryFrequency: {},
      seasonalPreferences: {},
      recentTrends: []
    };

    // 分析穿搭历史中的偏好
    if (wearHistory && wearHistory.length > 0) {
      wearHistory.forEach(record => {
        if (record.outfit && record.outfit.clothes) {
          record.outfit.clothes.forEach(item => {
            // 颜色偏好统计
            if (item.color) {
              analysis.colorFrequency[item.color] = (analysis.colorFrequency[item.color] || 0) + 1;
            }

            // 风格偏好统计
            if (item.style) {
              analysis.styleFrequency[item.style] = (analysis.styleFrequency[item.style] || 0) + 1;
            }

            // 品牌偏好统计
            if (item.brand) {
              analysis.brandFrequency[item.brand] = (analysis.brandFrequency[item.brand] || 0) + 1;
            }

            // 分类偏好统计
            if (item.category && item.category.name) {
              analysis.categoryFrequency[item.category.name] = (analysis.categoryFrequency[item.category.name] || 0) + 1;
            }
          });
        }
      });
    }

    // 分析用户设置的偏好
    if (preferences && preferences.length > 0) {
      preferences.forEach(pref => {
        if (pref.preference_type === 'color' && pref.preference_value) {
          analysis.colorFrequency[pref.preference_value] = (analysis.colorFrequency[pref.preference_value] || 0) + 5; // 用户设置的偏好权重更高
        }
        if (pref.preference_type === 'style' && pref.preference_value) {
          analysis.styleFrequency[pref.preference_value] = (analysis.styleFrequency[pref.preference_value] || 0) + 5;
        }
        if (pref.preference_type === 'brand' && pref.preference_value) {
          analysis.brandFrequency[pref.preference_value] = (analysis.brandFrequency[pref.preference_value] || 0) + 5;
        }
      });
    }

    // 提取最偏好的选项
    analysis.preferredColors = this.getTopPreferences(analysis.colorFrequency, 5);
    analysis.preferredStyles = this.getTopPreferences(analysis.styleFrequency, 3);
    analysis.preferredBrands = this.getTopPreferences(analysis.brandFrequency, 3);
    analysis.preferredCategories = this.getTopPreferences(analysis.categoryFrequency, 5);

    console.log('📊 用户偏好分析结果:', {
      colors: analysis.preferredColors,
      styles: analysis.preferredStyles,
      brands: analysis.preferredBrands
    });

    return analysis;
  }

  // 获取频率最高的偏好
  getTopPreferences(frequencyMap, limit = 5) {
    return Object.entries(frequencyMap)
      .sort(([,a], [,b]) => b - a)
      .slice(0, limit)
      .map(([key]) => key);
  }

  // 基于偏好分析生成个性化推荐
  generatePersonalizedRecommendations(clothing, analysis) {
    console.log('🎯 基于用户偏好生成个性化推荐...');

    // 根据偏好对衣服进行评分
    const scoredClothing = clothing.map(item => ({
      ...item,
      preferenceScore: this.calculatePreferenceScore(item, analysis)
    }));

    // 按偏好评分排序
    scoredClothing.sort((a, b) => b.preferenceScore - a.preferenceScore);

    // 选择评分较高的衣服生成搭配
    const topClothing = scoredClothing.slice(0, Math.min(20, scoredClothing.length));

    return this.generateOutfitCombinations(topClothing, {
      maxCombinations: 5,
      preferenceAnalysis: analysis
    });
  }

  // 计算单品的偏好评分
  calculatePreferenceScore(item, analysis) {
    let score = 0;

    // 颜色偏好评分
    if (item.color && analysis.preferredColors.includes(item.color)) {
      score += 3;
    }

    // 风格偏好评分
    if (item.style && analysis.preferredStyles.includes(item.style)) {
      score += 2;
    }

    // 品牌偏好评分
    if (item.brand && analysis.preferredBrands.includes(item.brand)) {
      score += 1;
    }

    // 分类偏好评分
    if (item.category && item.category.name && analysis.preferredCategories.includes(item.category.name)) {
      score += 1;
    }

    // 收藏状态加分
    if (item.is_favorite) {
      score += 2;
    }

    // 穿着频率加分（如果有穿着记录）
    if (item.wear_count && item.wear_count > 0) {
      score += Math.min(item.wear_count * 0.1, 1); // 最多加1分
    }

    return score;
  }

  // 综合智能推荐（集成AI分析）
  async getSmartRecommendations(userId, options = {}) {
    const { locationInfo, occasion, includeWeather = true, useAI = true } = options;

    try {
      // 获取用户位置信息
      let userLocation = locationInfo;
      if (!userLocation) {
        try {
          const ip = this.ctx.request.ip || this.ctx.ip;
          userLocation = await this.ctx.service.location.getLocationByIP(ip);
        } catch (error) {
          console.log('获取用户位置失败，使用默认位置');
          userLocation = this.ctx.service.location.getDefaultLocation();
        }
      }

      const city = userLocation.city || '北京';

      const result = {
        recommendations: [],
        weather: null,
        location: userLocation,
        analysis: {
          weatherBased: 0,
          personalBased: 0,
          occasionBased: 0,
          aiBased: 0
        },
        timestamp: Date.now(), // 添加时间戳确保每次请求不同
        requestId: Math.random().toString(36).substr(2, 9) // 添加请求ID
      };

      // 获取用户衣柜数据
      const userClothing = await this.getUserClothing(userId);
      console.log(`👕 用户${userId}的衣柜中有${userClothing.length}件衣服`);

      // 如果用户没有衣服，返回购买建议
      if (userClothing.length === 0) {
        return {
          recommendations: [],
          analysis: '您的衣柜还没有衣服呢！请先添加一些衣服，然后我就能为您生成个性化的搭配推荐了。',
          weather: includeWeather ? await this.getWeatherInfo(city) : null,
          source: '空衣柜提示'
        };
      }

      // 检查品类完整性
      const categoryAnalysis = this.analyzeCategoryCompleteness(userClothing);
      if (categoryAnalysis.missingCategories.length > 0) {
        result.categoryAdvice = {
          missing: categoryAnalysis.missingCategories,
          suggestions: categoryAnalysis.suggestions,
          message: `建议添加：${categoryAnalysis.missingCategories.join('、')}，让搭配更丰富！`
        };
        console.log(`💡 品类建议: ${result.categoryAdvice.message}`);
      }

      // 获取天气信息
      if (includeWeather) {
        result.weather = await this.getWeatherInfo(city);
        console.log(`🌤️ 天气信息: ${result.weather.temperature}°C ${result.weather.condition}`);
      }

      // 生成智能推荐（优先使用AI，失败时使用智能降级）
      try {
        const userProfile = await this.getUserProfile(userId);

        // 尝试AI推荐
        if (useAI) {
          console.log(`🤖 开始AI推荐，useAI=${useAI}`);
          const aiAnalysis = await this.ctx.service.aiAnalysis.analyzeOutfitRecommendation(
            userProfile,
            result.weather || { city, temperature: 20, condition: '晴' },
            userClothing,
            { occasion, requestId: result.requestId }
          );

          if (aiAnalysis.recommendations && aiAnalysis.recommendations.length > 0) {
            result.recommendations = aiAnalysis.recommendations;
            result.analysis.aiBased = aiAnalysis.recommendations.length;
            result.aiAnalysis = aiAnalysis.analysis;
            result.source = aiAnalysis.source || 'AI分析';
            console.log(`✅ AI推荐成功，生成${aiAnalysis.recommendations.length}个推荐`);
          } else {
            throw new Error('AI推荐返回空结果');
          }
        } else {
          throw new Error('AI推荐被禁用');
        }
      } catch (aiError) {
        console.log(`⚠️ AI推荐失败，使用智能降级: ${aiError.message}`);

        // 智能降级：基于规则的个性化推荐
        const smartRecommendations = await this.generateSmartRecommendations(
          userId,
          userClothing,
          result.weather,
          { occasion, requestId: result.requestId }
        );

        result.recommendations = smartRecommendations.recommendations;
        result.analysis.personalBased = smartRecommendations.recommendations.length;
        result.aiAnalysis = smartRecommendations.analysis;
        result.source = '智能推荐引擎';
      }

      // 去重并限制数量
      const uniqueRecommendations = this.deduplicateRecommendations(result.recommendations);
      result.recommendations = uniqueRecommendations.slice(0, 6);

      // 添加推荐理由
      result.recommendations = result.recommendations.map(rec => ({
        ...rec,
        reason: rec.reason || this.generateRecommendationReason(rec, result.weather, occasion)
      }));

      return result;
    } catch (error) {
      console.error('智能推荐失败:', error);
      throw error;
    }
  }

  // 生成智能推荐（降级方案）
  async generateSmartRecommendations(userId, clothingItems, weather, options = {}) {
    const { occasion, requestId } = options;

    console.log(`🧠 开始智能推荐生成，衣柜中有${clothingItems.length}件衣服`);

    // 按类别分组衣服
    const clothingByCategory = this.groupClothingByCategory(clothingItems);

    // 获取用户偏好
    const userProfile = await this.getUserProfile(userId);

    // 生成多样化的搭配组合
    const recommendations = [];
    const maxOutfits = 5;

    // 基于不同策略生成推荐
    const strategies = [
      { name: '经典搭配', weight: 0.3 },
      { name: '时尚潮流', weight: 0.25 },
      { name: '舒适休闲', weight: 0.25 },
      { name: '场合适宜', weight: 0.2 }
    ];

    for (let i = 0; i < maxOutfits; i++) {
      const strategy = strategies[i % strategies.length];
      const outfit = await this.generateOutfitByStrategy(
        clothingByCategory,
        weather,
        strategy,
        occasion,
        i
      );

      if (outfit && outfit.items.length >= 2) {
        outfit.requestId = requestId;
        outfit.timestamp = Date.now() + i; // 确保每个推荐都有不同的时间戳
        recommendations.push(outfit);
      }
    }

    return {
      recommendations,
      analysis: this.generateSmartAnalysis(clothingItems, weather, recommendations, userProfile),
      source: '智能推荐引擎'
    };
  }

  // 按类别分组衣服
  groupClothingByCategory(clothingItems) {
    const groups = {
      '上装': [],
      '下装': [],
      '外套': [],
      '鞋子': [],
      '配饰': [],
      // 保持英文键名兼容性
      tops: [],
      bottoms: [],
      outerwear: [],
      shoes: [],
      accessories: []
    };

    clothingItems.forEach(item => {
      const categoryName = item.category?.name?.toLowerCase() || '';

      if (['上装', 't恤', '衬衫', '毛衣', '卫衣', '背心'].some(cat => categoryName.includes(cat))) {
        groups['上装'].push(item);
        groups.tops.push(item);
      } else if (['下装', '裤子', '牛仔裤', '短裤', '裙子', '长裤'].some(cat => categoryName.includes(cat))) {
        groups['下装'].push(item);
        groups.bottoms.push(item);
      } else if (['外套', '夹克', '大衣', '风衣', '羽绒服'].some(cat => categoryName.includes(cat))) {
        groups['外套'].push(item);
        groups.outerwear.push(item);
      } else if (['鞋子', '运动鞋', '皮鞋', '靴子', '凉鞋'].some(cat => categoryName.includes(cat))) {
        groups['鞋子'].push(item);
        groups.shoes.push(item);
      } else if (['配饰', '帽子', '包包', '手表', '围巾'].some(cat => categoryName.includes(cat))) {
        groups['配饰'].push(item);
        groups.accessories.push(item);
      } else {
        // 默认分类
        if (categoryName.includes('鞋')) {
          groups['鞋子'].push(item);
          groups.shoes.push(item);
        } else {
          groups['上装'].push(item);
          groups.tops.push(item);
        }
      }
    });

    console.log('📊 衣服分类统计:', {
      上装: groups['上装'].length,
      下装: groups['下装'].length,
      外套: groups['外套'].length,
      鞋子: groups['鞋子'].length,
      配饰: groups['配饰'].length
    });

    return groups;
  }

  // 根据策略生成搭配
  async generateOutfitByStrategy(clothingByCategory, weather, strategy, occasion, index) {
    const { tops, bottoms, outerwear, shoes, accessories } = clothingByCategory;

    const outfit = {
      items: [],
      clothingIds: [],
      score: 0.8 + (Math.random() * 0.15), // 随机化分数
      tags: [strategy.name, '智能推荐'],
      strategy: strategy.name,
      reason: '',
      isRealClothing: true
    };

    // 选择上装（必需）
    if (tops.length > 0) {
      const top = this.selectItemByStrategy(tops, strategy, weather, index);
      if (top) {
        outfit.items.push(this.formatClothingItem(top));
        outfit.clothingIds.push(top.id);
      }
    }

    // 选择下装（必需）
    if (bottoms.length > 0) {
      const bottom = this.selectItemByStrategy(bottoms, strategy, weather, index);
      if (bottom) {
        outfit.items.push(this.formatClothingItem(bottom));
        outfit.clothingIds.push(bottom.id);
      }
    }

    // 根据天气选择外套
    if (weather && weather.temperature < 20 && outerwear.length > 0) {
      const outer = this.selectItemByStrategy(outerwear, strategy, weather, index);
      if (outer) {
        outfit.items.push(this.formatClothingItem(outer));
        outfit.clothingIds.push(outer.id);
      }
    }

    // 选择鞋子
    if (shoes.length > 0) {
      const shoe = this.selectItemByStrategy(shoes, strategy, weather, index);
      if (shoe) {
        outfit.items.push(this.formatClothingItem(shoe));
        outfit.clothingIds.push(shoe.id);
      }
    }

    // 生成搭配理由
    outfit.reason = this.generateOutfitReason(outfit.items, weather, strategy, occasion);

    return outfit;
  }

  // 去重推荐结果
  deduplicateRecommendations(recommendations) {
    const seen = new Set();
    return recommendations.filter(rec => {
      const key = rec.clothingIds ? rec.clothingIds.sort().join(',') : JSON.stringify(rec.items?.map(i => i.id).sort());
      if (seen.has(key)) {
        return false;
      }
      seen.add(key);
      return true;
    });
  }

  // 根据策略选择单品
  selectItemByStrategy(items, strategy, weather, index) {
    if (items.length === 0) return null;

    let selectedItem;

    switch (strategy.name) {
      case '经典搭配':
        // 选择经典颜色和款式
        selectedItem = items.find(item =>
          ['黑色', '白色', '灰色', '深蓝', '米色'].some(color =>
            item.color?.includes(color)
          )
        ) || items[index % items.length];
        break;

      case '时尚潮流':
        // 选择亮色或特殊款式
        selectedItem = items.find(item =>
          ['红色', '黄色', '绿色', '紫色', '粉色'].some(color =>
            item.color?.includes(color)
          )
        ) || items[(index + 1) % items.length];
        break;

      case '舒适休闲':
        // 选择舒适材质
        selectedItem = items.find(item =>
          ['棉', '针织', '运动', '休闲'].some(material =>
            item.name?.includes(material) || item.description?.includes(material)
          )
        ) || items[(index + 2) % items.length];
        break;

      case '场合适宜':
        // 根据场合选择
        selectedItem = items[(index + 3) % items.length];
        break;

      default:
        selectedItem = items[index % items.length];
    }

    return selectedItem;
  }

  // 生成搭配理由
  generateOutfitReason(items, weather, strategy, occasion) {
    const reasons = [];

    // 策略相关理由
    switch (strategy.name) {
      case '经典搭配':
        reasons.push('经典百搭，永不过时');
        break;
      case '时尚潮流':
        reasons.push('时尚前卫，彰显个性');
        break;
      case '舒适休闲':
        reasons.push('舒适自在，轻松惬意');
        break;
      case '场合适宜':
        reasons.push('得体大方，场合适宜');
        break;
    }

    // 天气相关理由
    if (weather) {
      const temp = weather.temperature;
      if (temp <= 10) {
        reasons.push('保暖御寒');
      } else if (temp <= 20) {
        reasons.push('温度适宜');
      } else if (temp <= 30) {
        reasons.push('清爽舒适');
      } else {
        reasons.push('凉爽透气');
      }
    }

    // 场合相关理由
    if (occasion) {
      reasons.push(`适合${occasion}`);
    }

    // 颜色搭配理由
    const colors = items.map(item => item.color).filter(Boolean);
    if (colors.length > 1) {
      const hasNeutral = colors.some(color =>
        ['黑色', '白色', '灰色', '米色'].some(neutral => color.includes(neutral))
      );
      if (hasNeutral) {
        reasons.push('颜色协调');
      }
    }

    return reasons.join('，') || '精心搭配推荐';
  }

  // 生成智能分析
  generateSmartAnalysis(clothingItems, weather, recommendations, userProfile) {
    const analysis = [];

    analysis.push('🎯 **智能搭配分析**\n');

    // 衣柜分析
    const categoryCount = {};
    clothingItems.forEach(item => {
      const category = item.category?.name || '其他';
      categoryCount[category] = (categoryCount[category] || 0) + 1;
    });

    analysis.push('👕 **衣柜概况**：');
    Object.entries(categoryCount).forEach(([category, count]) => {
      analysis.push(`• ${category}：${count}件`);
    });
    analysis.push('');

    // 天气分析
    if (weather) {
      analysis.push('🌤️ **天气适配**：');
      analysis.push(`• 当前温度：${weather.temperature}°C`);
      analysis.push(`• 天气状况：${weather.condition}`);

      if (weather.temperature <= 10) {
        analysis.push('• 建议：多层搭配，注意保暖');
      } else if (weather.temperature <= 20) {
        analysis.push('• 建议：适中厚度，可加外套');
      } else if (weather.temperature <= 30) {
        analysis.push('• 建议：轻薄透气，舒适为主');
      } else {
        analysis.push('• 建议：清凉材质，防晒降温');
      }
      analysis.push('');
    }

    // 推荐策略分析
    analysis.push('💡 **推荐策略**：');
    const strategies = [...new Set(recommendations.map(rec => rec.strategy))];
    strategies.forEach(strategy => {
      const count = recommendations.filter(rec => rec.strategy === strategy).length;
      analysis.push(`• ${strategy}：${count}套搭配`);
    });
    analysis.push('');

    // 个性化建议
    analysis.push('🌟 **个性化建议**：');
    analysis.push('• 每套搭配都基于您的真实衣柜');
    analysis.push('• 考虑了当前天气和场合需求');
    analysis.push('• 融合了多种风格策略');
    analysis.push('• 可以立即穿着，无需购买新衣服');

    return analysis.join('\n');
  }

  // 生成推荐理由
  generateRecommendationReason(recommendation, weather, occasion) {
    const reasons = [];

    if (weather) {
      const temp = weather.temperature;
      if (temp <= 10) {
        reasons.push('适合寒冷天气');
      } else if (temp <= 20) {
        reasons.push('适合凉爽天气');
      } else if (temp <= 30) {
        reasons.push('适合温暖天气');
      } else {
        reasons.push('适合炎热天气');
      }

      if (weather.condition.includes('雨')) {
        reasons.push('适合雨天');
      } else if (weather.condition.includes('晴')) {
        reasons.push('适合晴天');
      }
    }

    if (occasion) {
      reasons.push(`适合${occasion}场合`);
    }

    if (recommendation.score > 0.8) {
      reasons.push('高匹配度搭配');
    }

    return reasons.join('，') || '为您推荐';
  }

  // 格式化衣服数据，确保前端能正确渲染
  formatClothingItem(item) {
    return {
      id: item.id,
      name: item.name,
      color: item.color || '未知',
      brand: item.brand || '',
      style: item.style || '',
      season: item.season || '',
      image: item.image || '',
      category: item.category ? {
        id: item.category.id,
        name: item.category.name
      } : null,
      // 添加前端渲染需要的字段
      categoryName: item.category?.name || '其他',
      displayName: `${item.name} (${item.color || '未知'})`,
      // 保留原始数据
      ...item.dataValues || {}
    };
  }

  // 获取今日推荐
  async getTodayRecommendations(userId, locationInfo = null) {
    // 获取用户位置信息
    let userLocation = locationInfo;
    if (!userLocation) {
      try {
        // 尝试获取用户IP位置
        const ip = this.ctx.request.ip || this.ctx.ip;
        userLocation = await this.ctx.service.location.getLocationByIP(ip);
      } catch (error) {
        console.log('获取用户位置失败，使用默认位置');
        userLocation = this.ctx.service.location.getDefaultLocation();
      }
    }

    const city = userLocation.city || '北京';
    const weather = await this.getWeatherInfo(city);

    // 检查是否已有今日推荐
    const today = new Date().toISOString().split('T')[0];
    const existingRec = await this.ctx.model.Recommendation.findOne({
      where: {
        user_id: userId,
        type: 'daily',
        created_at: {
          [this.app.Sequelize.Op.gte]: today + ' 00:00:00',
          [this.app.Sequelize.Op.lt]: today + ' 23:59:59'
        }
      }
    });

    if (existingRec) {
      return {
        ...existingRec.toJSON(),
        weather,
        location: userLocation,
        recommendations: JSON.parse(existingRec.clothing_ids || '[]')
      };
    }

    // 使用本地随机算法生成今日推荐
    const todayRecs = await this.generateTodayRecommendations(userId, weather);

    // 保存今日推荐
    const recommendation = await this.ctx.model.Recommendation.create({
      user_id: userId,
      type: 'daily',
      title: `今日穿搭推荐 - ${weather.condition} ${weather.temperature}°C`,
      description: `根据今日天气和您的偏好为您推荐`,
      clothing_ids: JSON.stringify(todayRecs.recommendations),
      context: JSON.stringify({ weather, location: userLocation }),
      confidence_score: 0.85,
      expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000)
    });

    return {
      ...recommendation.toJSON(),
      weather,
      location: userLocation,
      recommendations: todayRecs.recommendations,
      analysis: todayRecs.analysis
    };
  }

  // 生成今日推荐（本地随机算法）
  async generateTodayRecommendations(userId, weather) {
    console.log(`🌅 开始生成今日推荐，用户ID: ${userId}`);

    // 获取用户衣柜数据
    const userClothing = await this.getUserClothing(userId);
    console.log(`👕 用户衣柜中有${userClothing.length}件衣服`);

    // 如果用户没有衣服，返回空推荐
    if (userClothing.length === 0) {
      return {
        recommendations: [],
        analysis: '您的衣柜还没有衣服呢！请先添加一些衣服，然后我就能为您生成今日推荐了。',
        source: '空衣柜提示'
      };
    }

    // 按类别分组衣服
    const clothingByCategory = this.groupClothingByCategory(userClothing);

    // 定义今日推荐策略
    const todayStrategies = [
      { name: '经典百搭', description: '永不过时的经典搭配', weight: 0.25 },
      { name: '舒适随性', description: '轻松舒适的日常穿搭', weight: 0.25 },
      { name: '简约时尚', description: '简洁大方的时尚造型', weight: 0.25 },
      { name: '个性表达', description: '展现个人风格的搭配', weight: 0.25 }
    ];

    // 生成推荐
    const recommendations = [];
    const maxOutfits = 5;

    for (let i = 0; i < maxOutfits; i++) {
      const strategy = todayStrategies[i % todayStrategies.length];
      const outfit = await this.generateTodayOutfitByStrategy(
        clothingByCategory,
        weather,
        strategy,
        i
      );

      if (outfit && outfit.items.length >= 2) {
        outfit.timestamp = Date.now() + i; // 确保每个推荐都有不同的时间戳
        recommendations.push(outfit);
      }
    }

    return {
      recommendations,
      analysis: this.generateTodayAnalysis(userClothing, weather, recommendations),
      source: '今日推荐算法'
    };
  }

  // 获取用户画像
  async getUserProfile(userId) {
    try {
      const user = await this.ctx.model.User.findByPk(userId);

      // 分析用户穿搭偏好
      const recentWears = await this.ctx.model.WearRecord.findAll({
        where: { user_id: userId },
        include: [{
          model: this.ctx.model.Outfit,
          as: 'outfit',
          attributes: ['style', 'season']
        }],
        order: [['created_at', 'DESC']],
        limit: 20
      });

      const styles = recentWears.map(w => w.outfit?.style).filter(Boolean);
      const preferredStyle = this.getMostFrequent(styles) || 'casual';

      return {
        ageGroup: user?.age_group || '25-35',
        occupation: user?.occupation || '上班族',
        preferredStyle,
        wearHistory: recentWears
      };
    } catch (error) {
      console.error('获取用户画像失败:', error);
      return {
        ageGroup: '25-35',
        occupation: '上班族',
        preferredStyle: 'casual'
      };
    }
  }

  // 获取用户衣服
  async getUserClothing(userId) {
    try {
      return await this.ctx.model.Clothing.findAll({
        where: { user_id: userId },
        include: [{
          model: this.ctx.model.Category,
          as: 'category'
        }],
        limit: 30
      });
    } catch (error) {
      console.error('获取用户衣服失败:', error);
      return [];
    }
  }

  // 获取最频繁的值
  getMostFrequent(arr) {
    if (arr.length === 0) return null;

    const frequency = {};
    arr.forEach(item => {
      frequency[item] = (frequency[item] || 0) + 1;
    });

    return Object.keys(frequency).reduce((a, b) =>
      frequency[a] > frequency[b] ? a : b
    );
  }

  // 根据类型获取衣服（支持多种分类名称）
  getClothesByType(clothingByCategory, typeNames) {
    for (const typeName of typeNames) {
      if (clothingByCategory[typeName] && clothingByCategory[typeName].length > 0) {
        return clothingByCategory[typeName];
      }
    }
    return [];
  }

  // 去除重复的搭配组合
  removeDuplicateCombinations(combinations) {
    const seen = new Set();
    return combinations.filter(combination => {
      const key = combination.clothingIds.sort().join(',');
      if (seen.has(key)) {
        return false;
      }
      seen.add(key);
      return true;
    });
  }

  // 根据策略生成今日搭配
  async generateTodayOutfitByStrategy(clothingByCategory, weather, strategy, index) {
    console.log(`🎯 使用策略 "${strategy.name}" 生成搭配 ${index + 1}`);

    const outfit = {
      name: `${strategy.name}搭配 ${index + 1}`,
      description: strategy.description,
      reason: strategy.name,
      items: [],
      clothingIds: [],
      score: 0.8 + Math.random() * 0.2, // 随机评分 0.8-1.0
      tags: [strategy.name],
      strategy: strategy.name
    };

    // 根据策略选择衣服
    const requiredCategories = ['tops', 'bottoms'];
    const optionalCategories = ['outerwear', 'shoes', 'accessories'];

    // 必需类别
    for (const category of requiredCategories) {
      const items = clothingByCategory[category] || [];
      if (items.length > 0) {
        const selectedItem = this.selectItemByTodayStrategy(items, strategy, index, weather);
        if (selectedItem) {
          outfit.items.push(selectedItem);
          outfit.clothingIds.push(selectedItem.id);
        }
      }
    }

    // 可选类别（随机添加）
    for (const category of optionalCategories) {
      const items = clothingByCategory[category] || [];
      if (items.length > 0 && Math.random() > 0.5) { // 50% 概率添加
        const selectedItem = this.selectItemByTodayStrategy(items, strategy, index, weather);
        if (selectedItem) {
          outfit.items.push(selectedItem);
          outfit.clothingIds.push(selectedItem.id);
        }
      }
    }

    return outfit;
  }

  // 根据今日策略选择单品
  selectItemByTodayStrategy(items, strategy, index, weather) {
    if (!items || items.length === 0) return null;

    let selectedItem;

    switch (strategy.name) {
      case '经典百搭':
        // 选择经典颜色和基础款式
        selectedItem = items.find(item =>
          ['黑色', '白色', '灰色', '深蓝', '米色', '卡其'].some(color =>
            item.color?.includes(color)
          )
        ) || items[index % items.length];
        break;

      case '舒适随性':
        // 选择舒适材质和休闲款式
        selectedItem = items.find(item =>
          ['棉', '针织', '运动', '休闲', '宽松'].some(keyword =>
            item.name?.includes(keyword) ||
            item.material?.includes(keyword) ||
            item.style === 'casual'
          )
        ) || items[(index + 1) % items.length];
        break;

      case '简约时尚':
        // 选择简洁设计和时尚元素
        selectedItem = items.find(item =>
          ['简约', '修身', '直筒', '时尚', '设计感'].some(keyword =>
            item.name?.includes(keyword) ||
            item.style === 'business'
          )
        ) || items[(index + 2) % items.length];
        break;

      case '个性表达':
        // 选择有特色的单品
        selectedItem = items.find(item =>
          ['印花', '图案', '亮色', '特色', '个性'].some(keyword =>
            item.name?.includes(keyword) ||
            ['红色', '黄色', '绿色', '紫色', '粉色', '橙色'].some(color =>
              item.color?.includes(color)
            )
          )
        ) || items[(index + 3) % items.length];
        break;

      default:
        selectedItem = items[index % items.length];
    }

    return selectedItem;
  }

  // 生成今日推荐分析
  generateTodayAnalysis(clothingItems, weather, recommendations) {
    const analysis = {
      totalClothing: clothingItems.length,
      recommendationCount: recommendations.length,
      weatherSuitability: weather ? `适合${weather.condition}天气` : '通用搭配',
      strategies: recommendations.map(rec => rec.strategy).filter(Boolean),
      avgScore: recommendations.length > 0
        ? (recommendations.reduce((sum, rec) => sum + rec.score, 0) / recommendations.length).toFixed(2)
        : 0
    };

    return `今日为您推荐了${analysis.recommendationCount}套搭配，包括${analysis.strategies.join('、')}等风格。基于您衣柜中的${analysis.totalClothing}件衣服，${analysis.weatherSuitability}，平均推荐度${analysis.avgScore}分。`;
  }

  // 智能天气搭配生成
  generateWeatherSmartOutfits(allClothing, weatherInfo) {
    const { weather, temperature } = weatherInfo;
    console.log(`🧠 开始智能天气搭配生成: ${temperature}°C ${weather}`);

    // 按分类分组衣服
    const clothingByCategory = this.groupClothingByCategory(allClothing);

    // 根据天气确定搭配策略
    const weatherStrategy = this.getWeatherStrategy(temperature, weather);
    console.log(`📋 天气策略:`, weatherStrategy);

    // 筛选适合天气的衣服
    const suitableClothing = this.filterClothingByWeatherStrategy(clothingByCategory, weatherStrategy);

    // 生成智能搭配
    const outfits = [];
    const maxOutfits = 5;

    for (let i = 0; i < maxOutfits; i++) {
      const outfit = this.createWeatherOutfit(suitableClothing, weatherStrategy, i);
      if (outfit && outfit.items.length >= 2) {
        outfit.timestamp = Date.now() + i;
        outfits.push(outfit);
      }
    }

    console.log(`✨ 生成了${outfits.length}个智能天气搭配`);
    return outfits;
  }

  // 获取天气策略
  getWeatherStrategy(temperature, weather) {
    const strategy = {
      temperature,
      weather,
      requiredLayers: [],
      preferredColors: [],
      avoidColors: [],
      materials: [],
      styles: []
    };

    // 根据温度确定层次
    if (temperature <= 0) {
      strategy.requiredLayers = ['内层', '中层', '外层'];
      strategy.preferredColors = ['深色', '暖色'];
      strategy.avoidColors = ['浅色', '冷色'];
      strategy.materials = ['羊毛', '羽绒', '厚棉'];
      strategy.styles = ['保暖', '厚重'];
    } else if (temperature <= 10) {
      strategy.requiredLayers = ['内层', '外层'];
      strategy.preferredColors = ['深色', '中性色'];
      strategy.avoidColors = ['纯白', '浅粉'];
      strategy.materials = ['毛衣', '夹克', '长裤'];
      strategy.styles = ['保暖', '层次'];
    } else if (temperature <= 20) {
      strategy.requiredLayers = ['内层', '可选外层'];
      strategy.preferredColors = ['中性色', '大地色'];
      strategy.materials = ['棉质', '针织', '薄外套'];
      strategy.styles = ['舒适', '休闲'];
    } else if (temperature <= 30) {
      strategy.requiredLayers = ['内层'];
      strategy.preferredColors = ['清爽色', '中性色'];
      strategy.materials = ['棉质', '透气'];
      strategy.styles = ['轻便', '透气'];
    } else {
      strategy.requiredLayers = ['内层'];
      strategy.preferredColors = ['浅色', '清爽色'];
      strategy.avoidColors = ['深黑', '厚重色'];
      strategy.materials = ['轻薄', '透气', '吸汗'];
      strategy.styles = ['清爽', '轻便'];
    }

    // 根据天气条件调整
    if (weather.includes('雪') || weather.includes('雨')) {
      strategy.requiredLayers.push('防水外层');
      strategy.preferredColors.push('深色');
      strategy.avoidColors.push('浅色', '白色');
    }

    return strategy;
  }

  // 根据天气策略筛选衣服
  filterClothingByWeatherStrategy(clothingByCategory, strategy) {
    const suitable = {};

    for (const [category, items] of Object.entries(clothingByCategory)) {
      suitable[category] = items.filter(item => {
        return this.isItemSuitableForWeather(item, strategy);
      });
    }

    return suitable;
  }

  // 判断单品是否适合天气
  isItemSuitableForWeather(item, strategy) {
    const { temperature, weather, preferredColors, avoidColors, materials, styles } = strategy;

    // 严寒天气检查（≤0°C）
    if (temperature <= 0) {
      // 严格排除不保暖的单品
      const unsuitableItems = [
        '短袖', '短裤', '薄', '凉鞋', '拖鞋', '背心', '吊带',
        '西装外套', '西装', '薄外套', '风衣', '单衣', '透气',
        '网眼', '镂空', '露', '薄款'
      ];

      if (unsuitableItems.some(keyword => item.name.includes(keyword))) {
        console.log(`❄️ 严寒天气排除: ${item.name} (温度${temperature}°C)`);
        return false;
      }

      // 外套类必须是保暖外套
      if (item.category?.name === '外套') {
        const warmOuterwear = ['羽绒', '棉衣', '毛呢', '厚', '保暖', '冬', '大衣'];
        if (!warmOuterwear.some(keyword => item.name.includes(keyword))) {
          console.log(`❄️ 严寒天气排除薄外套: ${item.name}`);
          return false;
        }
      }

      // 鞋子必须保暖
      if (item.category?.name === '鞋子') {
        const warmShoes = ['靴', '棉鞋', '雪地靴', '保暖'];
        const coldShoes = ['凉鞋', '拖鞋', '帆布鞋', '薄'];
        if (coldShoes.some(keyword => item.name.includes(keyword))) {
          console.log(`❄️ 严寒天气排除凉鞋: ${item.name}`);
          return false;
        }
      }
    }
    // 寒冷天气检查（1-10°C）
    else if (temperature <= 10) {
      // 排除明显不适合的单品
      const unsuitableItems = [
        '短袖', '短裤', '凉鞋', '拖鞋', '背心', '吊带', '薄款'
      ];

      if (unsuitableItems.some(keyword => item.name.includes(keyword))) {
        console.log(`🌨️ 寒冷天气排除: ${item.name} (温度${temperature}°C)`);
        return false;
      }

      // 西装外套在10°C以下不适合作为主要外套
      if (temperature <= 5 && item.name.includes('西装')) {
        console.log(`🌨️ 低温排除西装: ${item.name} (温度${temperature}°C)`);
        return false;
      }
    }
    // 炎热天气检查（≥25°C）
    else if (temperature >= 25) {
      // 炎热天气，避免厚重衣物
      const unsuitableItems = [
        '毛衣', '羽绒', '厚', '靴子', '长袖厚', '棉衣', '大衣', '保暖'
      ];

      if (unsuitableItems.some(keyword => item.name.includes(keyword))) {
        console.log(`☀️ 炎热天气排除: ${item.name} (温度${temperature}°C)`);
        return false;
      }
    }

    // 雨雪天气特殊检查
    if (weather && (weather.includes('雨') || weather.includes('雪'))) {
      // 避免容易湿透的材质和颜色
      if (item.color && ['白色', '浅色', '米色'].some(c => item.color.includes(c))) {
        console.log(`🌧️ 雨雪天气避免浅色: ${item.name}(${item.color})`);
        return false;
      }
    }

    // 颜色适宜性检查
    if (avoidColors.length > 0) {
      const itemColor = item.color?.toLowerCase() || '';
      for (const avoidColor of avoidColors) {
        if (avoidColor === '浅色' && ['白色', '米色', '浅灰', '浅蓝'].some(c => itemColor.includes(c))) {
          return false;
        }
        if (avoidColor === '深色' && ['黑色', '深蓝', '深灰', '深棕'].some(c => itemColor.includes(c))) {
          return false;
        }
        if (itemColor.includes(avoidColor)) {
          return false;
        }
      }
    }

    return true;
  }

  // 创建天气搭配
  createWeatherOutfit(suitableClothing, strategy, index) {
    const outfit = {
      name: `天气搭配 ${index + 1}`,
      description: this.generateWeatherOutfitDescription(strategy),
      reason: `适合${strategy.temperature}°C ${strategy.weather}天气`,
      items: [],
      clothingIds: [],
      score: 0.8,
      tags: ['天气推荐'],
      weatherStrategy: strategy.weather
    };

    // 必需的基础搭配：上装 + 下装
    const tops = suitableClothing['上装'] || [];
    const bottoms = suitableClothing['下装'] || [];

    if (tops.length === 0 || bottoms.length === 0) {
      console.log('⚠️ 缺少基础搭配单品');
      return null;
    }

    // 选择上装
    const selectedTop = tops[index % tops.length];
    outfit.items.push(selectedTop);
    outfit.clothingIds.push(selectedTop.id);

    // 选择下装
    const selectedBottom = bottoms[index % bottoms.length];
    outfit.items.push(selectedBottom);
    outfit.clothingIds.push(selectedBottom.id);

    // 根据天气策略添加外套
    if (strategy.temperature <= 15 || strategy.requiredLayers.includes('外层')) {
      const outerwear = suitableClothing['外套'] || [];
      if (outerwear.length > 0) {
        const selectedOuterwear = outerwear[index % outerwear.length];
        outfit.items.push(selectedOuterwear);
        outfit.clothingIds.push(selectedOuterwear.id);
      }
    }

    // 添加鞋子
    const shoes = suitableClothing['鞋子'] || [];
    if (shoes.length > 0) {
      const selectedShoes = shoes[index % shoes.length];
      outfit.items.push(selectedShoes);
      outfit.clothingIds.push(selectedShoes.id);
    }

    // 根据需要添加配饰
    if (strategy.temperature <= 10) {
      const accessories = suitableClothing['配饰'] || [];
      const warmAccessories = accessories.filter(item =>
        item.name.includes('围巾') || item.name.includes('帽子') || item.name.includes('手套')
      );
      if (warmAccessories.length > 0) {
        const selectedAccessory = warmAccessories[index % warmAccessories.length];
        outfit.items.push(selectedAccessory);
        outfit.clothingIds.push(selectedAccessory.id);
      }
    }

    // 计算搭配评分
    outfit.score = this.calculateWeatherOutfitScore(outfit, strategy);

    return outfit;
  }

  // 生成天气搭配描述
  generateWeatherOutfitDescription(strategy) {
    const { temperature, weather } = strategy;

    if (temperature <= 0) {
      return '严寒天气保暖搭配，多层次穿搭保温';
    } else if (temperature <= 10) {
      return '寒冷天气温暖搭配，注意保暖防风';
    } else if (temperature <= 20) {
      return '凉爽天气舒适搭配，轻松自在';
    } else if (temperature <= 30) {
      return '温和天气清爽搭配，舒适透气';
    } else {
      return '炎热天气清凉搭配，轻薄透气';
    }
  }

  // 计算天气搭配评分
  calculateWeatherOutfitScore(outfit, strategy) {
    let score = 0.7; // 基础分

    // 温度适宜性加分
    const hasAppropriateClothing = outfit.items.some(item => {
      if (strategy.temperature <= 10) {
        return item.name.includes('毛衣') || item.name.includes('外套') || item.name.includes('长裤');
      } else if (strategy.temperature >= 25) {
        return item.name.includes('T恤') || item.name.includes('短') || item.name.includes('薄');
      }
      return true;
    });

    if (hasAppropriateClothing) score += 0.1;

    // 颜色协调性加分
    const colors = outfit.items.map(item => item.color).filter(Boolean);
    if (this.areColorsHarmonious(colors)) score += 0.1;

    // 层次合理性加分
    if (strategy.temperature <= 15 && outfit.items.some(item => item.category?.name === '外套')) {
      score += 0.1;
    }

    return Math.min(score, 1.0);
  }

  // 判断颜色是否协调
  areColorsHarmonious(colors) {
    if (colors.length <= 1) return true;

    // 简单的颜色协调判断
    const neutralColors = ['黑色', '白色', '灰色', '米色', '卡其'];
    const hasNeutral = colors.some(color => neutralColors.some(nc => color.includes(nc)));

    // 如果有中性色，通常比较好搭配
    if (hasNeutral) return true;

    // 同色系搭配
    const colorFamilies = {
      blue: ['蓝色', '深蓝', '浅蓝', '天蓝'],
      red: ['红色', '深红', '粉红', '酒红'],
      green: ['绿色', '深绿', '浅绿', '军绿'],
      brown: ['棕色', '深棕', '浅棕', '咖啡']
    };

    for (const family of Object.values(colorFamilies)) {
      if (colors.every(color => family.some(fc => color.includes(fc)))) {
        return true;
      }
    }

    return false;
  }

  // 场合推荐相关方法
  generateOccasionSmartOutfits(allClothing, occasionInfo) {
    const { occasion, style } = occasionInfo;
    console.log(`🎭 开始生成场合搭配: ${occasion}`);

    // 按分类分组衣服
    const clothingByCategory = this.groupClothingByCategory(allClothing);

    // 根据场合确定搭配策略
    const occasionStrategy = this.getOccasionStrategy(occasion, style);
    console.log(`📋 场合策略:`, occasionStrategy);

    // 筛选适合场合的衣服
    const suitableClothing = this.filterClothingByOccasion(clothingByCategory, occasionStrategy);

    // 生成场合搭配
    const outfits = [];
    const maxOutfits = 5;

    for (let i = 0; i < maxOutfits; i++) {
      const outfit = this.createOccasionOutfit(suitableClothing, occasionStrategy, i);
      if (outfit && outfit.items.length >= 2) {
        outfit.timestamp = Date.now() + i;
        outfits.push(outfit);
      }
    }

    console.log(`✨ 生成了${outfits.length}个场合搭配`);
    return outfits;
  }

  // 获取场合策略
  getOccasionStrategy(occasion, style) {
    const strategies = {
      work: {
        name: '工作场合',
        requiredStyles: ['business', 'formal'],
        preferredColors: ['黑色', '深蓝', '灰色', '白色'],
        avoidColors: ['亮色', '荧光色'],
        formalLevel: 'high',
        accessories: ['腰带', '包包']
      },
      date: {
        name: '约会场合',
        requiredStyles: ['romantic', 'elegant', 'casual'],
        preferredColors: ['粉色', '白色', '浅色', '温柔色'],
        avoidColors: ['过于正式的黑色'],
        formalLevel: 'medium',
        accessories: ['包包', '饰品']
      },
      party: {
        name: '聚会场合',
        requiredStyles: ['party', 'trendy', 'fashion'],
        preferredColors: ['亮色', '时尚色', '个性色'],
        avoidColors: ['过于朴素的颜色'],
        formalLevel: 'medium',
        accessories: ['饰品', '包包']
      },
      casual: {
        name: '休闲场合',
        requiredStyles: ['casual', 'relaxed', 'comfortable'],
        preferredColors: ['任意颜色'],
        avoidColors: [],
        formalLevel: 'low',
        accessories: ['帽子', '包包']
      },
      formal: {
        name: '正式场合',
        requiredStyles: ['formal', 'elegant', 'business'],
        preferredColors: ['黑色', '深蓝', '白色', '灰色'],
        avoidColors: ['休闲色', '亮色'],
        formalLevel: 'very_high',
        accessories: ['腰带', '正式包包']
      },
      sport: {
        name: '运动场合',
        requiredStyles: ['sport', 'athletic', 'comfortable'],
        preferredColors: ['运动色', '活力色'],
        avoidColors: ['正式色'],
        formalLevel: 'very_low',
        accessories: ['运动包', '帽子']
      }
    };

    return strategies[occasion] || strategies.casual;
  }

  // 根据场合筛选衣服
  filterClothingByOccasion(clothingByCategory, strategy) {
    const suitable = {};

    for (const [category, items] of Object.entries(clothingByCategory)) {
      const originalCount = items.length;
      suitable[category] = items.filter(item => {
        return this.isItemSuitableForOccasion(item, strategy);
      });
      console.log(`🔍 ${category}: ${originalCount} → ${suitable[category].length} 件适合${strategy.name}`);
    }

    return suitable;
  }

  // 判断单品是否适合场合
  isItemSuitableForOccasion(item, strategy) {
    // 颜色检查 - 只检查明确避免的颜色
    if (item.color && strategy.avoidColors.length > 0) {
      for (const avoidColor of strategy.avoidColors) {
        if (item.color.includes(avoidColor)) {
          return false;
        }
      }
    }

    // 风格检查 - 如果没有风格信息，默认允许
    // 只有明确不符合的才排除
    if (item.style && strategy.requiredStyles.length > 0) {
      // 对于休闲场合，允许大部分风格
      if (strategy.name === '休闲场合') {
        return !['formal', 'business'].includes(item.style);
      }
      // 对于正式场合，只允许正式风格
      if (strategy.name === '正式场合' || strategy.name === '工作场合') {
        return ['formal', 'business', 'elegant'].includes(item.style) || !item.style;
      }
    }

    return true; // 默认允许
  }

  // 创建场合搭配
  createOccasionOutfit(suitableClothing, strategy, index) {
    const outfit = {
      name: `${strategy.name}搭配 ${index + 1}`,
      description: this.generateOccasionOutfitDescription(strategy),
      reason: `适合${strategy.name}的搭配`,
      items: [],
      clothingIds: [],
      score: 0.8,
      tags: [strategy.name],
      occasion: strategy.name
    };

    // 基础搭配：上装 + 下装
    const tops = suitableClothing['上装'] || [];
    const bottoms = suitableClothing['下装'] || [];

    if (tops.length === 0 || bottoms.length === 0) {
      return null;
    }

    // 选择上装和下装
    const selectedTop = tops[index % tops.length];
    const selectedBottom = bottoms[index % bottoms.length];

    outfit.items.push(selectedTop, selectedBottom);
    outfit.clothingIds.push(selectedTop.id, selectedBottom.id);

    // 根据正式程度添加外套
    if (strategy.formalLevel === 'high' || strategy.formalLevel === 'very_high') {
      const outerwear = suitableClothing['外套'] || [];
      if (outerwear.length > 0) {
        const selectedOuterwear = outerwear[index % outerwear.length];
        outfit.items.push(selectedOuterwear);
        outfit.clothingIds.push(selectedOuterwear.id);
      }
    }

    // 添加鞋子
    const shoes = suitableClothing['鞋子'] || [];
    if (shoes.length > 0) {
      const selectedShoes = shoes[index % shoes.length];
      outfit.items.push(selectedShoes);
      outfit.clothingIds.push(selectedShoes.id);
    }

    // 添加配饰
    const accessories = suitableClothing['配饰'] || [];
    if (accessories.length > 0 && Math.random() > 0.3) {
      const selectedAccessory = accessories[index % accessories.length];
      outfit.items.push(selectedAccessory);
      outfit.clothingIds.push(selectedAccessory.id);
    }

    return outfit;
  }

  // 生成场合搭配描述
  generateOccasionOutfitDescription(strategy) {
    const descriptions = {
      '工作场合': '专业干练的职场搭配，展现专业形象',
      '约会场合': '温柔优雅的约会搭配，展现个人魅力',
      '聚会场合': '时尚亮眼的聚会搭配，成为焦点',
      '休闲场合': '轻松舒适的休闲搭配，享受自在时光',
      '正式场合': '庄重优雅的正式搭配，彰显品味',
      '运动场合': '活力十足的运动搭配，释放运动激情'
    };

    return descriptions[strategy.name] || '精心搭配的造型';
  }

  // 颜色搭配相关方法
  generateColorSmartOutfits(allClothing, colorInfo) {
    const { baseColor, colorScheme } = colorInfo;
    console.log(`🌈 开始生成颜色搭配: ${baseColor} - ${colorScheme}`);

    // 按分类分组衣服
    const clothingByCategory = this.groupClothingByCategory(allClothing);

    // 根据颜色方案确定搭配策略
    const colorStrategy = this.getColorStrategy(baseColor, colorScheme);
    console.log(`🎨 颜色策略:`, colorStrategy);

    // 筛选符合颜色方案的衣服
    const suitableClothing = this.filterClothingByColor(clothingByCategory, colorStrategy);

    // 生成颜色搭配
    const outfits = [];
    const maxOutfits = 5;

    for (let i = 0; i < maxOutfits; i++) {
      const outfit = this.createColorOutfit(suitableClothing, colorStrategy, i);
      if (outfit && outfit.items.length >= 2) {
        outfit.timestamp = Date.now() + i;
        outfits.push(outfit);
      }
    }

    console.log(`✨ 生成了${outfits.length}个颜色搭配`);
    return outfits;
  }

  // 获取颜色策略
  getColorStrategy(baseColor, colorScheme) {
    const strategy = {
      baseColor,
      colorScheme,
      allowedColors: [],
      primaryColors: [],
      accentColors: [],
      neutralColors: ['黑色', '白色', '灰色', '米色']
    };

    switch (colorScheme) {
      case 'monochromatic':
        strategy.allowedColors = this.getMonochromaticColors(baseColor);
        strategy.primaryColors = [baseColor];
        break;
      case 'complementary':
        strategy.allowedColors = this.getComplementaryColors(baseColor);
        strategy.primaryColors = [baseColor];
        strategy.accentColors = strategy.allowedColors.filter(c => c !== baseColor);
        break;
      case 'analogous':
        strategy.allowedColors = this.getAnalogousColors(baseColor);
        strategy.primaryColors = strategy.allowedColors;
        break;
      case 'triadic':
        strategy.allowedColors = this.getTriadicColors(baseColor);
        strategy.primaryColors = strategy.allowedColors;
        break;
      default:
        strategy.allowedColors = [...strategy.neutralColors, baseColor];
        strategy.primaryColors = [baseColor];
    }

    // 总是包含中性色
    strategy.allowedColors = [...new Set([...strategy.allowedColors, ...strategy.neutralColors])];

    return strategy;
  }

  // 根据颜色筛选衣服
  filterClothingByColor(clothingByCategory, strategy) {
    const suitable = {};

    console.log(`🎨 允许的颜色: ${strategy.allowedColors.join(', ')}`);

    for (const [category, items] of Object.entries(clothingByCategory)) {
      const originalCount = items.length;
      suitable[category] = items.filter(item => {
        const isOk = this.isItemSuitableForColor(item, strategy);
        if (!isOk && originalCount <= 5) { // 只在衣服较少时显示详细信息
          console.log(`❌ ${item.name}(${item.color}) 不符合颜色方案`);
        }
        return isOk;
      });
      console.log(`🔍 ${category}: ${originalCount} → ${suitable[category].length} 件符合颜色方案`);
    }

    return suitable;
  }

  // 判断单品是否适合颜色方案
  isItemSuitableForColor(item, strategy) {
    if (!item.color) return true; // 没有颜色信息的默认允许

    const itemColor = item.color.toLowerCase();

    // 中性色总是允许
    const neutralColors = ['黑色', '白色', '灰色', '米色', '卡其'];
    if (neutralColors.some(neutral => itemColor.includes(neutral.toLowerCase()))) {
      return true;
    }

    // 检查是否在允许的颜色列表中
    const isAllowed = strategy.allowedColors.some(allowedColor =>
      itemColor.includes(allowedColor.toLowerCase()) ||
      allowedColor.toLowerCase().includes(itemColor)
    );

    // 如果不在允许列表中，但是单色搭配，允许基础色
    if (!isAllowed && strategy.colorScheme === 'monochromatic') {
      return itemColor.includes(strategy.baseColor.toLowerCase());
    }

    return isAllowed;
  }

  // 创建颜色搭配
  createColorOutfit(suitableClothing, strategy, index) {
    const outfit = {
      name: `${strategy.baseColor} ${this.getColorSchemeDisplayName(strategy.colorScheme)} ${index + 1}`,
      description: this.generateColorOutfitDescription(strategy),
      reason: `基于${strategy.baseColor}的${this.getColorSchemeDisplayName(strategy.colorScheme)}`,
      items: [],
      clothingIds: [],
      score: 0.8,
      tags: ['颜色搭配'],
      colorScheme: strategy.colorScheme
    };

    // 基础搭配：上装 + 下装
    const tops = suitableClothing['上装'] || [];
    const bottoms = suitableClothing['下装'] || [];

    if (tops.length === 0 || bottoms.length === 0) {
      return null;
    }

    // 智能选择颜色搭配
    const selectedTop = this.selectItemByColor(tops, strategy, 'primary', index);
    const selectedBottom = this.selectItemByColor(bottoms, strategy, 'neutral', index);

    if (selectedTop && selectedBottom) {
      outfit.items.push(selectedTop, selectedBottom);
      outfit.clothingIds.push(selectedTop.id, selectedBottom.id);
    } else {
      return null;
    }

    // 添加其他单品
    const shoes = suitableClothing['鞋子'] || [];
    if (shoes.length > 0) {
      const selectedShoes = this.selectItemByColor(shoes, strategy, 'neutral', index);
      if (selectedShoes) {
        outfit.items.push(selectedShoes);
        outfit.clothingIds.push(selectedShoes.id);
      }
    }

    return outfit;
  }

  // 根据颜色角色选择单品
  selectItemByColor(items, strategy, colorRole, index) {
    if (items.length === 0) return null;

    let targetColors = [];

    switch (colorRole) {
      case 'primary':
        targetColors = strategy.primaryColors;
        break;
      case 'accent':
        targetColors = strategy.accentColors;
        break;
      case 'neutral':
        targetColors = strategy.neutralColors;
        break;
      default:
        targetColors = strategy.allowedColors;
    }

    console.log(`🎨 选择${colorRole}颜色单品，目标颜色: ${targetColors.join(', ')}`);

    // 优先选择目标颜色的单品
    const preferredItems = items.filter(item => {
      if (!item.color) return false;

      const itemColor = item.color.toLowerCase();
      const isMatch = targetColors.some(color => {
        const targetColor = color.toLowerCase();
        // 更灵活的颜色匹配
        return itemColor.includes(targetColor) ||
               targetColor.includes(itemColor) ||
               this.isColorSimilar(itemColor, targetColor);
      });

      if (isMatch) {
        console.log(`✅ 匹配: ${item.name}(${item.color})`);
      }

      return isMatch;
    });

    if (preferredItems.length > 0) {
      const selected = preferredItems[index % preferredItems.length];
      console.log(`🎯 选中: ${selected.name}(${selected.color})`);
      return selected;
    }

    // 如果没有首选颜色，选择任意允许的颜色
    console.log(`⚠️ 没有找到目标颜色，使用备选方案`);
    return items[index % items.length];
  }

  // 判断颜色是否相似
  isColorSimilar(color1, color2) {
    // 蓝色系匹配
    const blueColors = ['蓝', 'blue', '深蓝', '浅蓝', '天蓝', '海蓝', '宝蓝'];
    const isColor1Blue = blueColors.some(blue => color1.includes(blue));
    const isColor2Blue = blueColors.some(blue => color2.includes(blue));

    if (isColor1Blue && isColor2Blue) return true;

    // 红色系匹配
    const redColors = ['红', 'red', '深红', '浅红', '粉红', '玫红', '酒红'];
    const isColor1Red = redColors.some(red => color1.includes(red));
    const isColor2Red = redColors.some(red => color2.includes(red));

    if (isColor1Red && isColor2Red) return true;

    // 绿色系匹配
    const greenColors = ['绿', 'green', '深绿', '浅绿', '军绿', '橄榄绿'];
    const isColor1Green = greenColors.some(green => color1.includes(green));
    const isColor2Green = greenColors.some(green => color2.includes(green));

    if (isColor1Green && isColor2Green) return true;

    return false;
  }

  // 生成颜色搭配描述
  generateColorOutfitDescription(strategy) {
    const descriptions = {
      monochromatic: '单色系搭配，简约统一的视觉效果',
      complementary: '互补色搭配，对比鲜明的时尚造型',
      analogous: '类似色搭配，和谐自然的色彩层次',
      triadic: '三角色搭配，活力丰富的色彩组合'
    };

    return descriptions[strategy.colorScheme] || '精心设计的颜色搭配';
  }

  // 辅助方法
  getOccasionDisplayName(occasion) {
    const names = {
      work: '工作',
      date: '约会',
      party: '聚会',
      casual: '休闲',
      formal: '正式',
      sport: '运动'
    };
    return names[occasion] || occasion;
  }

  getColorSchemeDisplayName(scheme) {
    const names = {
      monochromatic: '单色搭配',
      complementary: '互补色搭配',
      analogous: '类似色搭配',
      triadic: '三角色搭配'
    };
    return names[scheme] || '颜色搭配';
  }

  // 颜色理论方法
  getMonochromaticColors(baseColor) {
    // 单色系：同一颜色的不同深浅
    const colorMap = {
      '红色': ['红色', '深红', '浅红', '粉红'],
      '蓝色': ['蓝色', '深蓝', '浅蓝', '天蓝'],
      '绿色': ['绿色', '深绿', '浅绿', '薄荷绿'],
      '黄色': ['黄色', '深黄', '浅黄', '柠檬黄'],
      '紫色': ['紫色', '深紫', '浅紫', '薰衣草'],
      '黑色': ['黑色', '深灰', '中灰', '浅灰'],
      '白色': ['白色', '米白', '奶白', '象牙白']
    };

    return colorMap[baseColor] || [baseColor, '黑色', '白色', '灰色'];
  }

  getComplementaryColors(baseColor) {
    // 互补色：色轮上相对的颜色
    const complementMap = {
      '红色': ['红色', '绿色', '白色', '黑色'],
      '蓝色': ['蓝色', '橙色', '白色', '黑色'],
      '绿色': ['绿色', '红色', '白色', '黑色'],
      '黄色': ['黄色', '紫色', '白色', '黑色'],
      '紫色': ['紫色', '黄色', '白色', '黑色'],
      '橙色': ['橙色', '蓝色', '白色', '黑色']
    };

    return complementMap[baseColor] || [baseColor, '白色', '黑色', '灰色'];
  }

  getAnalogousColors(baseColor) {
    // 类似色：色轮上相邻的颜色
    const analogousMap = {
      '红色': ['红色', '橙色', '粉色', '白色'],
      '蓝色': ['蓝色', '绿色', '紫色', '白色'],
      '绿色': ['绿色', '蓝色', '黄色', '白色'],
      '黄色': ['黄色', '绿色', '橙色', '白色'],
      '紫色': ['紫色', '蓝色', '红色', '白色'],
      '橙色': ['橙色', '红色', '黄色', '白色']
    };

    return analogousMap[baseColor] || [baseColor, '白色', '黑色', '灰色'];
  }

  getTriadicColors(baseColor) {
    // 三角色：色轮上等距的三个颜色
    const triadicMap = {
      '红色': ['红色', '蓝色', '黄色', '白色'],
      '蓝色': ['蓝色', '红色', '黄色', '白色'],
      '黄色': ['黄色', '红色', '蓝色', '白色'],
      '绿色': ['绿色', '紫色', '橙色', '白色'],
      '紫色': ['紫色', '绿色', '橙色', '白色'],
      '橙色': ['橙色', '绿色', '紫色', '白色']
    };

    return triadicMap[baseColor] || [baseColor, '白色', '黑色', '灰色'];
  }

  // 分析品类完整性
  analyzeCategoryCompleteness(clothingItems) {
    console.log('📊 开始分析衣柜品类完整性...');

    // 按分类分组
    const clothingByCategory = this.groupClothingByCategory(clothingItems);

    // 定义基础品类需求
    const essentialCategories = {
      '上装': {
        name: '上装',
        minCount: 3,
        suggestions: ['T恤', '衬衫', '毛衣', '卫衣']
      },
      '下装': {
        name: '下装',
        minCount: 2,
        suggestions: ['牛仔裤', '休闲裤', '正装裤']
      },
      '外套': {
        name: '外套',
        minCount: 1,
        suggestions: ['夹克', '大衣', '羽绒服']
      },
      '鞋子': {
        name: '鞋子',
        minCount: 2,
        suggestions: ['运动鞋', '皮鞋', '靴子']
      },
      '配饰': {
        name: '配饰',
        minCount: 1,
        suggestions: ['包包', '腰带', '围巾', '帽子']
      }
    };

    const analysis = {
      missingCategories: [],
      insufficientCategories: [],
      suggestions: [],
      completeness: 0
    };

    let totalScore = 0;
    let maxScore = Object.keys(essentialCategories).length;

    for (const [categoryKey, requirement] of Object.entries(essentialCategories)) {
      const currentCount = clothingByCategory[categoryKey]?.length || 0;

      console.log(`📁 ${requirement.name}: ${currentCount} 件 (建议${requirement.minCount}件以上)`);

      if (currentCount === 0) {
        analysis.missingCategories.push(requirement.name);
        analysis.suggestions.push(`添加${requirement.name}：${requirement.suggestions.slice(0, 2).join('、')}等`);
      } else if (currentCount < requirement.minCount) {
        analysis.insufficientCategories.push({
          category: requirement.name,
          current: currentCount,
          recommended: requirement.minCount
        });
        analysis.suggestions.push(`增加${requirement.name}：目前${currentCount}件，建议${requirement.minCount}件以上`);
        totalScore += 0.5; // 部分分数
      } else {
        totalScore += 1; // 满分
      }
    }

    analysis.completeness = Math.round((totalScore / maxScore) * 100);

    console.log(`📊 衣柜完整度: ${analysis.completeness}%`);
    console.log(`❌ 缺少品类: ${analysis.missingCategories.join('、') || '无'}`);
    console.log(`⚠️ 不足品类: ${analysis.insufficientCategories.map(item => `${item.category}(${item.current}/${item.recommended})`).join('、') || '无'}`);

    return analysis;
  }
}

module.exports = RecommendationService;
